package rtmp;

import amf.AMFUtil;
import util.Common;
import util.MsgType;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送控制请求
 */
public class RtmpRequestControl {

    private ChannelHandlerContext ctx;

    private int chunkLength = Common.DEFAULT_CHUNK_MESSAGE_LENGTH;

    public RtmpRequestControl(ChannelHandlerContext ctx, int chunkLength) {
        this.ctx = ctx;
        this.chunkLength = chunkLength;
    }

    public void play() throws IOException {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(1024);

        buffer.writeBytes(AMFUtil.writeString("play"));
        buffer.writeBytes(AMFUtil.writeNumber(0));
        buffer.writeByte(AMFUtil.writeNull());
        byte[] version = new byte[buffer.readableBytes()];
        buffer.readBytes(version);
        byte[] statusData = AMFUtil.writeString("home");

        handData(MsgType.MSG_CONTROL, version, statusData, 0);
    }

    public void connect() throws IOException {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(1024);
        buffer.writeBytes(AMFUtil.writeString("connect"));
        buffer.writeBytes(AMFUtil.writeNumber(1));
        byte[] version = new byte[buffer.readableBytes()];
        buffer.readBytes(version);
        Map<String, Object> status = new HashMap<String, Object>();
        status.put("app", "live");

        status.put("flashver", "LNX 9,0,124,2");
        status.put("tcUrl", "rtmp://192.168.0.147:9999/live");
        status.put("fpad", false);
        status.put("capabilities",15.0);
        status.put("audioCodecs",4071.0);
        status.put("videoCodecs",4071.0);
        status.put("Name: videoFunction",1.0);

        byte[] statusData = AMFUtil.writeObject(status);
        handData(MsgType.MSG_CONTROL, version, statusData, 0);
    }

    private void handData(byte msgType, byte[] version, byte[] status, int streamId) throws IOException {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(1024);
        buffer.writeBytes(version);
        buffer.writeBytes(status);
        int length = buffer.readableBytes();
        byte[] data = new byte[length];
        buffer.readBytes(data);
        RtmpResponse.sendData(data, msgType, streamId, ctx, 0, chunkLength);
        buffer.clear();
    }
}
